<template>
  <div class="me-view-body" v-title :data-title="title">
    <el-container class="me-view-container">
      <el-main>
        <div class="me-view-card">
          <h1 class="me-view-title">{{ article.title }}</h1>
          <div class="me-view-author">
            <a class="">
              <img class="me-view-picture" :src="article.avatar" />
            </a>
            <div class="me-view-info">
              <span>{{ article.userName }}</span>
              <div class="me-view-meta">
                <span>{{ article.createTime | format }}</span>
                <span>点赞 {{ article.likeCount }}</span>
                <span>评论 {{ article.commentNum }}</span>
              </div>
            </div>
            <el-button
              v-if="this.article.userId == this.comment.userId"
              @click="editArticle()"
              style="position: absolute; left: 60%"
              size="mini"
              type="success"
              round
              icon="el-icon-edit"
              >编辑</el-button
            >
          </div>

          <div class="me-view-content">
            <markdown-editor :editor="article.editor"></markdown-editor>
          </div>
          <!-- <div class="markdown-body" v-html="article.content"></div> -->
          <div class="me-view-tag">
            标签：
            <el-tag
              v-for="t in article.tags"
              :key="t.id"
              class="me-view-tag-item"
              size="mini"
              type="success"
              >{{ t.name }}</el-tag
            >
            <div class="dianzan" @click="toLike">
              <img src="static/category/dianzan.png" alt="" v-show="!isLike" />
              <img src="static/category/adianzan.png" alt="" v-show="isLike" />
            </div>
          </div>
          <div class="me-view-end">
            <el-alert
              title="文章End..."
              type="success"
              center
              :closable="false"
            >
            </el-alert>
          </div>

          <!-- <div class="me-view-tag">
            文章分类：
            <el-button @click="tagOrCategory('category', article.category.id)" size="mini" type="primary" round plain>{{article.category.categoryName}}</el-button>
          </div> -->

          <div class="me-view-comment">
            <div class="me-view-comment-write">
              <el-row :gutter="20">
                <el-col :span="2">
                  <a class="">
                    <img class="me-view-picture" :src="avatar" />
                  </a>
                </el-col>
                <el-col :span="21">
                  <el-input
                    type="textarea"
                    :autosize="{ minRows: 2 }"
                    placeholder="你的评论..."
                    class="me-view-comment-text"
                    v-model="comment.content"
                    resize="none"
                  >
                  </el-input>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="3" :offset="21">
                  <el-button
                    type="text"
                    @click="addComment()"
                    style="margin-top: 5px"
                    >评论</el-button
                  >
                </el-col>
              </el-row>
            </div>

            <div class="me-view-comment-title">
              <span>{{ article.commentNum }} 条评论</span>
            </div>

            <commment-item
              v-for="(c, index) in comments"
              :comment="c"
              :articleId="article.id"
              :index="index"
              :userId="comment.userId"
              :childComments="c.childComments"
              :rootCommentCounts="comments.length"
              @commentCountsIncrement="commentCountsIncrement"
              :key="c.id"
            >
            </commment-item>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import "github-markdown-css/github-markdown.css";
import MarkdownEditor from "@/components/markdown/MarkdownEditor";
import CommmentItem from "@/components/comment/CommentItem";
import { viewArticle } from "@/api/article";
import { addLike, cancelLike, getLike } from "@/api/like";
import { getCommentsByBlogId, addComment } from "@/api/comment";
import { Message } from "element-ui";
import default_avatar from "@/assets/img/default_avatar.png";

export default {
  name: "BlogView",
  watch: {
    $route: "getArticle",
  },
  data() {
    return {
      article: {
        id: "",
        title: "",
        commentNum: 0,
        likeCount: 0,
        description: "",
        updateTime: "",
        userName: "",
        userId: 0,
        avatar: "",
        content: "",
        tags: [],
        // category: {},
        editor: {
          value: "",
          toolbarsFlag: false,
          subfield: false,
          defaultOpen: "preview",
        },
      },
      comments: [],
      comment: {
        blogId: 0,
        content: "",
        levelFlag: "1",
        userId: 0,
      },
      userId: 0,
      isLike: false,
    };
  },
  components: {
    "markdown-editor": MarkdownEditor,
    CommmentItem,
  },
  computed: {
    avatar() {
      let avatar = this.article.avatar;
      if (avatar) {
        return avatar;
      }
      return default_avatar;
    },
    title() {
      return `${this.article.title} - 文章 - 洋芋博客`;
    },
  },
  created() {
    if (this.$store.getters.getUser) {
      this.comment.userId = this.$store.getters.getUser.id;
    }
    this.getArticle();
  },

  methods: {
    getLike(blogId) {
      let data = { blogId: blogId, userId: this.comment.userId };
      let that = this;
      getLike(data)
        .then((rsp) => {
          if (rsp.data) {
            this.isLike = true;
          }
        })
        .catch((error) => {
          if (error !== "error") {
            that.$message({
              type: "error",
              message: "获取点赞信息失败",
              showClose: true,
            });
          }
        });
    },
    toLike() {
      if (this.comment.userId == 0) {
        Message({
          type: "warning",
          showClose: true,
          message: "请先登录哦",
        });
      } else {
        let data = { blogId: this.article.id, userId: this.comment.userId };
        let that = this;
        if (this.isLike) {
          //已点赞，现取消点赞
          cancelLike(data)
            .then((data) => {
              this.isLike = !this.isLike;
            })
            .catch((error) => {
              if (error !== "error") {
                that.$message({
                  type: "error",
                  message: "取消点赞失败",
                  showClose: true,
                });
              }
            });
        } else {
          //未点赞，现点赞
          addLike(data)
            .then((data) => {
              this.isLike = !this.isLike;
            })
            .catch((error) => {
              if (error !== "error") {
                that.$message({
                  type: "error",
                  message: "点赞失败",
                  showClose: true,
                });
              }
            });
        }
      }
    },
    tagOrCategory(type, id) {
      this.$router.push({ path: `/${type}/${id}` });
    },
    editArticle() {
      this.$router.push({ path: `/write/${this.article.id}` });
    },
    getArticle() {
      let that = this;
      console.log(that.$route.params);
      viewArticle(that.$route.params.id)
        .then((data) => {
          Object.assign(that.article, data.data);
          that.article.editor.value = data.data.content;

          that.getCommentsByBlogId();
          that.getLike(data.data.id);
        })
        .catch((error) => {
          if (error !== "error") {
            that.$message({
              type: "error",
              message: "文章加载失败",
              showClose: true,
            });
          }
        });
    },
    addComment() {
      if (this.comment.userId == 0) {
        Message({
          type: "warning",
          showClose: true,
          message: "请先登录哦",
        });
      } else {
        let that = this;
        if (!that.comment.content) {
          return;
        }
        that.comment.blogId = that.article.id;

        addComment(that.comment)
          .then((data) => {
            that.$message({
              type: "success",
              message: "评论成功",
              showClose: true,
            });
            that.comments.unshift(data.data);
            that.commentCountsIncrement();
            that.comment.content = "";
            //this.getCommentsByBlogId();
          })
          .catch((error) => {
            if (error !== "error") {
              that.$message({
                type: "error",
                message: "评论失败",
                showClose: true,
              });
            }
          });
      }
    },
    getCommentsByBlogId() {
      let that = this;
      getCommentsByBlogId(that.article.id)
        .then((data) => {
          that.comments = data.data;
        })
        .catch((error) => {
          if (error !== "error") {
            that.$message({
              type: "error",
              message: "评论加载失败",
              showClose: true,
            });
          }
        });
    },
    commentCountsIncrement() {
      this.article.commentCounts += 1;
    },
  },
  //组件内的守卫 调整body的背景色
  beforeRouteEnter(to, from, next) {
    window.document.body.style.backgroundColor = "#fff";
    next();
  },
  beforeRouteLeave(to, from, next) {
    window.document.body.style.backgroundColor = "#f5f5f5";
    next();
  },
};
</script>

<style>
.me-view-body {
  margin: 100px auto 140px;
}

.me-view-container {
  width: 1000px;
}

.el-main {
  overflow: hidden;
}

.me-view-title {
  font-size: 34px;
  font-weight: 700;
  line-height: 1.3;
}

.me-view-author {
  /*margin: 30px 0;*/
  margin-top: 30px;
  vertical-align: middle;
}

.me-view-picture {
  width: 40px;
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 50%;
  vertical-align: middle;
  background-color: #5fb878;
}

.me-view-info {
  display: inline-block;
  vertical-align: middle;
  margin-left: 8px;
}

.me-view-meta {
  font-size: 12px;
  color: #969696;
}

.me-view-end {
  margin-top: 20px;
  padding-right: 25px;
}

.me-view-tag {
  margin-top: 20px;
  padding-left: 6px;
  border-left: 4px solid #c5cac3;
  position: relative;
}
.dianzan {
  position: absolute;
  right: 20px;
  top: 5px;
}

.me-view-tag img {
  width: 30px;
  height: auto;
}

.me-view-tag-item {
  margin: 0 4px;
}

.me-view-comment {
  margin-top: 60px;
}

.me-view-comment-title {
  font-weight: 600;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 20px;
}

.me-view-comment-write {
  margin-top: 20px;
}

.me-view-comment-text {
  font-size: 16px;
}

.v-show-content {
  padding: 8px 25px 15px 0px !important;
}

.v-note-wrapper .v-note-panel {
  box-shadow: none !important;
}

.v-note-wrapper .v-note-panel .v-note-show .v-show-content,
.v-note-wrapper .v-note-panel .v-note-show .v-show-content-html {
  background: #fff !important;
}
.me-view-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 100%;
  min-height: 700px;
  margin: 10px auto;
  padding: 20px 15px;
}
</style>
